package com.xiaojie.demo;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import static com.xiaojie.cofnig.RabbitMQConfig.DEMO_ROUTE_KEY;
import static com.xiaojie.cofnig.RabbitMQConfig.ITEM_TOPIC_EXCHANGE;

/**
 * @author wangye
 * @classname Sender
 * @date 2021/4/12 15:29
 **/
@RestController
@RequestMapping("/demo")
public class Sender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息并确认
     *
     * @param msg
     * @auther xiaojie
     * @date 2021/4/14
     */
    @RequestMapping(value = "send", method = RequestMethod.GET)
    public void sendMessage(String msg) throws Exception {
        //发送消息并确认是否发送到mq节点成功
        //即使返回成功但并不能保证交换器能正确路由到队列
        CorrelationData correlationData = new CorrelationData();
        correlationData.getFuture().addCallback((result) -> {
            if (result.isAck()) {
                System.out.println("发送消息成功");
            } else {
                System.out.println("发送消息失败:" + result.getReason());
            }
        }, (ex) -> {
            ex.printStackTrace();
        });


        rabbitTemplate.convertAndSend(ITEM_TOPIC_EXCHANGE, DEMO_ROUTE_KEY, msg, (message) -> {
                    //对单独的消息设置过期时间，如果消息所在的队列也设置了过期时间，过期时间小的生效，单位毫秒
                    message.getMessageProperties().setExpiration("5000");
                    return message;
                }
                , correlationData);
    }

    @RequestMapping(value = "send2", method = RequestMethod.GET)
    public void sendMessage2(String msg,String rounteKey) throws Exception {
        //发送消息并确认是否发送到mq节点成功
        //即使返回成功但并不能保证交换器能正确路由到队列
        CorrelationData correlationData = new CorrelationData();
        correlationData.getFuture().addCallback((result) -> {
            if (result.isAck()) {
                System.out.println("发送消息成功");
            } else {
                System.out.println("发送消息失败:" + result.getReason());
            }
        }, (ex) -> {
            ex.printStackTrace();
        });


        rabbitTemplate.convertAndSend("xverse-test", rounteKey, msg, (message) -> {
                    //对单独的消息设置过期时间，如果消息所在的队列也设置了过期时间，过期时间小的生效，单位毫秒
                    message.getMessageProperties().setExpiration("5000");
                    return message;
                }
                , correlationData);
    }


}
